package com.example.pages;

import static org.openqa.selenium.support.ui.ExpectedConditions.alertIsPresent;
import com.google.common.collect.*;
import java.util.List;

import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;

import com.example.tests.SortedListOf;
import com.example.tests.User;
	
public class UserPage extends InternalPage {
	@FindBy(name = "username")
	public WebElement NewUserNameField;
	
	@FindBy(name = "email")
	public WebElement NewEmailField;
	
	@FindBy(name = "submit")
	public WebElement saveButton;
	
	@FindBy(tagName = "Edit admin")
	public WebElement editAdmin;
	
		
	@FindBy(name = "email")
	public WebElement EmailField;
	
	@FindBy(name = "password")
	public WebElement NewPasswordField;
	
	@FindBy(name = "password2")
	public WebElement AgainPasswordField;
	
	@FindBy(css = "h3 + table > tbody> tr")
	public java.util.List<WebElement> userRows;
	
	
	public UserPage createNewUser(User user) {
        //create new user (guest role)
		NewUserNameField.sendKeys(user.name);
        EmailField.sendKeys(user.email);
        NewPasswordField.sendKeys(user.password);
        AgainPasswordField.sendKeys(user.password);
        saveButton.click();
        cachedUsers = null;
        return MyPageFactory.getPage(driver, UserPage.class);
       
       } 
	
	public UserPage deleteNewUser(User user) {
       for (WebElement row : userRows) {
        	if(user.equals(convertRowToUser(row))) {
        		row.findElement(By.xpath("./td[6]/a")).click();
        		wait_for().until(alertIsPresent()).accept();
        break;
        	}
        }
        cachedUsers = null;
		return MyPageFactory.getPage(driver, UserPage.class);
    }

		  private SortedListOf<User> cachedUsers;
		  
		  public SortedListOf<User> getUsers() {
		    if (cachedUsers == null) {
		      cachedUsers = new SortedListOf<User>();
		      for (WebElement row : userRows) {
		        cachedUsers.add(convertRowToUser(row));
		      }
		    }

		    return new SortedListOf<User>(cachedUsers);
		  }
		  
		  public int getUserCount() {
		    return userRows.size();
		  }

		  private User convertRowToUser(WebElement row) {
		    List<WebElement> cells = row.findElements(By.tagName("td"));
		    return new User()
		      .withName(cells.get(1).getText())
		      .withEmail(cells.get(2).getText())
		      .withRole(cells.get(3).getText());
		  }
		
}









